#pragma once
#include"MY_API.hpp"
#include<mutex>
#include<unordered_map>
#include<websocketpp/server.hpp>
#include<websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> web_server_t;

class online_manage{
private:
    //用户管理要加锁保证原子性
    std::mutex _mutex;
    //游戏大厅用户管理
    std::unordered_map<int, web_server_t::connection_ptr> _hall_user;
    //游戏房间用户管理
    std::unordered_map<int, web_server_t::connection_ptr> _room_user;

public:
    void enter_hall(int uid, web_server_t::connection_ptr& connect)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        _hall_user.insert(std::make_pair(uid, connect));
    }

    std::unordered_map<int, web_server_t::connection_ptr> get_room_user()
    {
        return _room_user;
    }

    void enter_room(int uid, web_server_t::connection_ptr& connect)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        _room_user.insert(std::make_pair(uid, connect));
    }

    void exit_hall(int uid)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        _hall_user.erase(uid);
    }

    void exit_room(int uid)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        _room_user.erase(uid);
    }

    bool is_in_hall(int uid)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        auto pos = _hall_user.find(uid);
        if (pos == _hall_user.end())
            return false;
        return true;
    }

    bool is_in_room(int uid)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        auto pos = _room_user.find(uid);
        if (pos == _room_user.end())
            return false;
        return true;
    }

    web_server_t::connection_ptr get_connect_from_hall(int uid)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        auto pos = _hall_user.find(uid);
        if (pos == _hall_user.end())
            return web_server_t::connection_ptr();
        return pos->second;
    }

    web_server_t::connection_ptr get_connect_from_room(int uid)
    {
        std::unique_lock<std::mutex> _mt(_mutex);
        auto pos = _room_user.find(uid);
        if (pos == _room_user.end())
            return web_server_t::connection_ptr();
        return pos->second;
    }
};

